﻿using System;
using System.Data;
using System.Collections;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AnyOffice.Components;
using AnyOffice.DAL;
using AnyOffice.Model;
using AnyOffice.BIZ;
using log4net;
using System.Reflection;
using Microsoft.ApplicationBlocks.Data;

namespace AnyOffice.general.report.manage
{
    public partial class week_edit : ModulePage
    {
        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected void btnAddFile_Click(object sender, EventArgs e)
        {
            if (this.fileAttach.PostedFile.ContentLength > 0)
            {
                try
                {
                    string uniqueTempPath = this.ViewState["UniqueTempPath"].ToString();
                    if (uniqueTempPath == "")
                    {
                        uniqueTempPath = AttachmentBiz.GetUniqueTempPath();
                        this.ViewState["UniqueTempPath"] = uniqueTempPath;
                    }
                    Upload upload = new Upload();
                    upload.OverwriteFile = true;
                    upload.DestinationPath = uniqueTempPath;
                    upload.GetFile(this.fileAttach.PostedFile);
                    upload.DoUpload();
                    this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) + upload.FileSize;
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    this.ViewState["FileList"] = list;
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) + 1;
                    this.ltbFileList.Items.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) != 0)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) > 0)
                    {
                        this.pnlAttach.Visible = true;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("附件添加", exception);
                    }
                }
            }
        }
        protected void btnRemoveFile_Click(object sender, EventArgs e)
        {
            if (this.ltbFileList.Items.Count != 0)
            {
                try
                {
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Remove(this.ltbFileList.SelectedItem.Text);
                    this.ViewState["FileList"] = list;
                    string fileName = this.ViewState["UniqueTempPath"].ToString() + this.ltbFileList.SelectedItem.Text;
                    FileInfo info = new FileInfo(fileName);
                    if (info.Exists)
                    {
                        this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) - info.Length;
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) - 1;
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) >= 1)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    this.ltbFileList.Items.Remove(this.ltbFileList.SelectedItem.Text);
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) == 0)
                    {
                        if (Directory.Exists(this.ViewState["UniqueTempPath"].ToString()))
                        {
                            Directory.Delete(this.ViewState["UniqueTempPath"].ToString());
                        }
                        this.ViewState["UniqueTempPath"] = "";
                        this.pnlAttach.Visible = false;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("附件删除", exception);
                    }
                }
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            this.pnlMain.Visible = false;
            string attachmentId = "";
            try
            {
                if (this.ViewState["OldAttachmentId"].ToString() != string.Empty)
                {
                    AttachmentBiz.DeleteByAttachmendId(base.Conn, this.ViewState["OldAttachmentId"].ToString());
                }
                if (this.ViewState["UniqueTempPath"].ToString() != "")
                {
                    string uniquePath = AttachmentBiz.GetUniquePath(out attachmentId);
                    Directory.Move(this.ViewState["UniqueTempPath"].ToString(), uniquePath);
                    AttachmentData data = new AttachmentData();
                    AttachmentDao dao = new AttachmentDao();
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    for (int i = 0; i < list.Count; i++)
                    {
                        FileInfo info = new FileInfo(uniquePath + list[i].ToString());
                        if (info.Exists)
                        {
                            data.Type = 8;
                            data.AttachmentId = attachmentId;
                            data.Name = info.Name;
                            data.AddTime = DateTime.Now;
                            data.TotalSize = (int)info.Length;
                            data.UserId = base.User.Identity.Name;
                            dao.Insert(base.Conn, data);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("表单提交 - 附件上传相关", exception);
                }
            }
            ReportDao dao2 = new ReportDao();
            ReportData data2 = new ReportData();
            data2.ReportId = Convert.ToInt32(this.ViewState["ReportId"].ToString());
            data2.UserId = base.User.Identity.Name;
            if (attachmentId != string.Empty)
            {
                data2.AttachmentId = attachmentId;
            }
            data2.Title = this.txtTitle.Text;
            data2.Type = 1;
            data2.ReportTime = DateTime.Now;
            if (this.txtNote1.Text != string.Empty)
            {
                data2.Note1 = this.txtNote1.Text;
            }
            if (this.txtNote2.Text != string.Empty)
            {
                data2.Note2 = this.txtNote2.Text;
            }
            if (this.txtNote3.Text != string.Empty)
            {
                data2.Note3 = this.txtNote3.Text;
            }
            //if (this.txtNote4.Text != string.Empty)
            //{
            //    data2.Note4 = this.txtNote4.Text;
            //}
            data2.Note4 = "";


            //项目名称
            if (!string.IsNullOrEmpty(ddlProductName.SelectedValue))
            {
                data2.PlanID = Convert.ToInt16(ddlProductName.SelectedValue);
            }

            data2.Year = Convert.ToInt16(ddYear.SelectedValue);

            data2.Month = Convert.ToInt16(ddlMonth.SelectedValue);


            if (this.ToId.Value != string.Empty)
            {
                data2.Managers = this.ToId.Value;
            }
            dao2.Update(base.Conn, data2);
            if ((this.ckbSms.Checked || this.ckbMobile.Checked) && (this.ToId.Value != string.Empty))
            {
                SmsData data3 = new SmsData();
                SmsDao dao3 = new SmsDao();
                data3.Type = 15;
                data3.FromId = base.User.Identity.Name;
                data3.ToIdList = this.ToId.Value;
                data3.Content = "请查看周报！\n标题：" + this.txtTitle.Text;
                data3.RemindFlag = true;
                data3.SendTime = DateTime.Now;
                dao3.BizSend(base.Conn, data3, this.ckbSms.Checked, this.ckbMobile.Checked);
            }
            this.litMessage.Text = base.ShowPrompt("周报修改成功！", "index1.aspx?page=" + this.ViewState["CurrentPage"].ToString());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                int num = (Request.QueryString["page"] != null) ? int.Parse(Request.QueryString["page"]) : 1;
                this.ViewState["CurrentPage"] = num;
                int reportId = (Request.QueryString["report_id"] != null) ? int.Parse(Request.QueryString["report_id"]) : 0;
                this.ViewState["ReportId"] = reportId;
                DataTable table = new ReportDao().SelectByReportId(base.Conn, reportId);
                if (table.Rows.Count == 0)
                {
                    this.pnlMain.Visible = false;
                    this.litMessage.Text = base.ShowPrompt("无此周报", "index1.aspx?type_id=" + this.ViewState["TypeId"].ToString() + "&page=" + num.ToString());
                }
                else if (table.Rows[0]["UserId"].ToString() != base.User.Identity.Name)
                {
                    this.pnlMain.Visible = false;
                    this.litMessage.Text = base.ShowPromptClose("无此周报");
                }
                else
                {
                    this.txtTitle.Text = table.Rows[0]["Title"].ToString();
                    //this.txtReportTime.Value = Convert.ToDateTime(table.Rows[0]["ReportTime"].ToString()).ToString("yyyy-MM-dd");



                    string[] _years = { (DateTime.Now.Year - 1).ToString(), DateTime.Now.Year.ToString(), (DateTime.Now.Year + 1).ToString() };

                    foreach (string _str in _years)
                    {
                        ddYear.Items.Add(new ListItem(_str, _str));
                    }
                    if (ddYear.Items.FindByValue(table.Rows[0]["Year"].ToString()) != null)
                    {
                        ddYear.ClearSelection();
                        ddYear.Items.FindByValue(table.Rows[0]["Year"].ToString()).Selected = true;
                    }


                    string commandText = @"select planid,[name] from Plan_Work where (CHARINDEX(',' +'" + base.User.Identity.Name + @"'+ ',',',' + CAST([Plan_Work].Manager AS nvarchar(2000)) + ',') > 0) 
                                      and  CompletedPercent<>10 and Status<>2  ORDER BY [Plan_Work].[PlanId] DESC";
                    DataTable _table = SqlHelper.ExecuteDataset(base.Conn, CommandType.Text, commandText).Tables[0];

                    if (table.Rows.Count > 0)
                    {
                        ddlProductName.DataSource = _table;
                        ddlProductName.DataValueField = "planid";
                        ddlProductName.DataTextField = "name";
                        this.ddlProductName.DataBind();
                    }
                    // Convert.ToInt32(table.Rows[0]["PlanID"].ToString())

                    if (ddlProductName.Items.FindByValue(table.Rows[0]["PlanID"].ToString()) != null)
                    {
                        ddlProductName.ClearSelection();
                        ddlProductName.Items.FindByValue(table.Rows[0]["PlanID"].ToString()).Selected = true;

                    }


                    string[] _months = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
                    foreach (string _str in _months)
                    {
                        if (Convert.ToInt16(_str) <= DateTime.Now.Month)
                        {
                            ddlMonth.Items.Add(new ListItem(_str, _str));
                        }
                    }
                    if (ddlMonth.Items.FindByValue(table.Rows[0]["Month"].ToString()) != null)
                    {
                        ddlMonth.ClearSelection();
                        ddlMonth.Items.FindByValue(table.Rows[0]["Month"].ToString()).Selected = true;
                    }





                    if (table.Rows[0]["Note1"] != DBNull.Value)
                    {
                        this.txtNote1.Text = table.Rows[0]["Note1"].ToString();
                    }
                    if (table.Rows[0]["Note2"] != DBNull.Value)
                    {
                        this.txtNote2.Text = table.Rows[0]["Note2"].ToString();
                    }
                    if (table.Rows[0]["Note3"] != DBNull.Value)
                    {
                        this.txtNote3.Text = table.Rows[0]["Note3"].ToString();
                    }
                    //if (table.Rows[0]["Note4"] != DBNull.Value)
                    //{
                    //    this.txtNote4.Text = table.Rows[0]["Note4"].ToString();
                    //}
                    if (table.Rows[0]["Managers"] != DBNull.Value)
                    {
                        this.ToId.Value = table.Rows[0]["Managers"].ToString();
                    }
                    if ((table.Rows[0]["ManagerNames"] != DBNull.Value) && (table.Rows[0]["ManagerNames"].ToString() != string.Empty))
                    {
                        this.ToName.Value = table.Rows[0]["ManagerNames"].ToString() + ",";
                    }
                    string attachmentId = (table.Rows[0]["AttachmentId"] != DBNull.Value) ? table.Rows[0]["AttachmentId"].ToString() : "";
                    this.ViewState["FileNums"] = 0;
                    this.ViewState["FileList"] = new ArrayList();
                    this.ViewState["UniqueTempPath"] = "";
                    this.ViewState["TotalSize"] = 0;
                    this.btnAddFile.Attributes.Add("onclick", "return CheckFile();");
                    this.ViewState["OldAttachmentId"] = attachmentId;
                    if (attachmentId != string.Empty)
                    {
                        DataTable table2 = new AttachmentDao().SelectByAttachmentId(base.Conn, attachmentId);
                        if (table2.Rows.Count > 0)
                        {
                            try
                            {
                                this.ViewState["FileNums"] = table2.Rows.Count;
                                ArrayList list = new ArrayList();
                                string savedPath = AttachmentBiz.GetSavedPath(attachmentId);
                                string uniqueTempPath = AttachmentBiz.GetUniqueTempPath();
                                this.ViewState["UniqueTempPath"] = uniqueTempPath;
                                AttachmentBiz.Copy(savedPath, uniqueTempPath);
                                int num3 = 0;
                                for (int i = 0; i < table2.Rows.Count; i++)
                                {
                                    list.Add(table2.Rows[i]["Name"].ToString());
                                    num3 += Convert.ToInt32(table2.Rows[i]["TotalSize"].ToString());
                                }
                                this.ltbFileList.DataSource = list;
                                this.ltbFileList.DataBind();
                                this.ltbFileList.Rows = table2.Rows.Count;
                                this.ViewState["FileList"] = list;
                                this.ViewState["TotalSize"] = num3;
                                this.pnlAttach.Visible = true;
                            }
                            catch (Exception exception)
                            {
                                if (log.IsErrorEnabled)
                                {
                                    log.Error("提交前 - 附件上传相关", exception);
                                }
                            }
                        }
                    }
                    this.btnSubmit.Attributes.Add("onclick", "return CheckForm();");
                    this.ckbMobile.Visible = SmsDao.IsMobile(SmsDao.SmsType.Report);
                }
            }
        }


 

    }
}
